package com.mobimap.nhom9.dao;

import java.util.ArrayList;
import java.util.List;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.mobimap.nhom9.dao.table.AddressTable;
import com.mobimap.nhom9.dto.PlaceExDTO;

public class AddressDAO extends OneKeyTableDAO<PlaceExDTO> {

	private static final AddressTable info = new AddressTable();

	public AddressDAO(SQLiteDatabase db) {
		super(db, info);

	}

	/*
	 * public List<PlaceExDTO> timDiaChi(String tuKhoa) { List<PlaceExDTO> kq =
	 * null; String query = SqlHelper.FormatParamSql(tuKhoa); List<String>
	 * numberAndStreet = StringHelper.getNumberAndStreet(query);
	 * 
	 * String selection = String.format("Area LIKE '%%%s%%'",
	 * numberAndStreet.get(1)); if (numberAndStreet.get(0).length() > 0) {
	 * selection += String.format(" AND Number = '%s'", numberAndStreet.get(0));
	 * }
	 * 
	 * kq = getDTOs(selection, table); return kq; }
	 */
	public List<PlaceExDTO> timDiaChi(String keyword) {
		String params = StringHelper.FormatParamSql(keyword);
		List<String> numberAndStreet = getNumberAndStreet(params);

		String query = "SELECT Address.* FROM Address, KeyAddress WHERE Address.ID=KeyAddress.AddressId";

		String selection = String.format(" AND KeyAddress.Area LIKE '%%%s%%'",
				numberAndStreet.get(1));
		if (numberAndStreet.get(0).length() > 0) {
			selection += String.format(" AND Address.Number = '%s'",
					numberAndStreet.get(0));
		}
		query += selection;

		Log.e("MOBIMAP", "query: " + query);
		Cursor cursor = database.rawQuery(query, null);
		cursor.moveToFirst();
		List<PlaceExDTO> lstAddress = QueryHelper.cursorToDTOs(cursor, table);
		return lstAddress;
	}

	public static List<String> getNumberAndStreet(String keyword) {
		List<String> result = new ArrayList<String>();
		if (Character.isDigit(keyword.charAt(0))) {
			int i = keyword.indexOf(' ');
			if (i == -1) {
				result.add("");
				result.add(keyword);
			} else {
				result.add(keyword.substring(0, i));
				result.add(keyword.substring(i + 1));
			}

		} else {
			result.add("");
			result.add(keyword);
		}

		return result;
	}
}
